package cn.itcast.bassm.service.impl;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.itcast.bassm.mapper.PushMapper;
import cn.itcast.bassm.mapper.UserMapper;
import cn.itcast.bassm.pojo.Location;
import cn.itcast.bassm.pojo.Returnxx;
import cn.itcast.bassm.pojo.Shooting;
import cn.itcast.bassm.pojo.Unitdoor;
import cn.itcast.bassm.pojo.Uploadfile;
import cn.itcast.bassm.pojo.User;
import cn.itcast.bassm.pojo.Userformation;
import cn.itcast.bassm.pojo.Usero;
import cn.itcast.bassm.pojo.Visitors;
import cn.itcast.bassm.pojo.pathuser;
import cn.itcast.bassm.pojo.test1;
import cn.itcast.bassm.service.UserService;
import cn.itcast.bassm.util.Page;
import cn.itcast.bassm.util.readTxT;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;


@Service
public class UserServiceImpl implements UserService {
	private static Logger mLogger = Logger.getLogger("UserServiceImpl");
	String Localfaceuser="admin";
	String passwork="123456";
	private final String CONTENT_TYPE_TEXT_JSON = "text/json";
	//private long dbid = 10001;
	

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private PushMapper pushMapper;
	
	public User queryUserById(int id) {
		return userMapper.queryUserById(id);
	}
	
	/**
	 * 根据用户查询，返回用户对应的权限和小区地址
	 */
	public Userformation queryUserByPowrd(String username, String password) {
		String nuber1="1";
		String nuber2="2";
		String nuber3="3";
		String msg;
		String yusername=username;
		String ypassword=password;
		Userformation userformation = new Userformation();
		User user=userMapper.queryUserByPowrd(yusername, ypassword);
		if(user==null){
			msg="1";
			userformation.setMsg(msg);
			return userformation;
		}else{
			if(user.getYnumber().equalsIgnoreCase(nuber1)){
				msg="200";
				userformation.setMsg(msg);
				userformation.setNumbers(user.getYaddress());
				userformation.setQx(nuber1);
				return userformation;
			}
			if(user.getYnumber().equalsIgnoreCase(nuber2)){
				msg="200";
				Cookie c=new Cookie("users", username);
				
				//设置过期时间
				c.setMaxAge(6000);
				userformation.setDuixiang(c);
				userformation.setMsg(msg);
				userformation.setNumbers(user.getYaddress());
				userformation.setQx(nuber2);
				
				return userformation;
			}
			if(user.getYnumber().equalsIgnoreCase(nuber3)){
				msg="200";
				userformation.setMsg(msg);
				userformation.setNumbers(user.getYaddress());
				userformation.setQx(nuber3);
				return userformation;
			}
			
			
		}
		msg="0";
		userformation.setMsg(msg);
	
        
		return userformation;	
	}
	
	
	public String addAlarmCallBak(){
		 String txtPath ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
		 String TimeSex=readTxT.readTxtLine(txtPath, 1);
		 String calbackurl=TimeSex+"/bassm/user/savemsg";
		  List<NameValuePair> params = new ArrayList<NameValuePair>();
	        params.add(new BasicNameValuePair("url", ""+calbackurl));
	        params.add(new BasicNameValuePair("enable", "true"));
	        params.add(new BasicNameValuePair("alarmOnly", "false"));
	        boolean ret =  false;
	        String json =doBasicAuthPost( params);
	        if (json != null) {
	            JsonParser parser = new JsonParser(); // 创建JSON解析器
	            JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
	            int errorcode = object.get("errorCode").getAsInt();
	            if (errorcode == 0) {
	                ret = true;
	                String msg="成功";
	    	        return msg;
	            }
	            mLogger.info(json);
	        } else {
	            mLogger.error("connect addAlarmCallBak error");
	        }
	        String msg="成功";
	        return msg;
	    }
	       
	
	
	
	 public String doBasicAuthPost( List<NameValuePair> params) {
		   String result = null;
		   String txtPath ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
		   String TimeSex=readTxT.readTxtLine(txtPath, 1);
		   String alarmCallbackServer=TimeSex+"/api/v1/alarm/httpCallback";
	        HttpPost httpPost = new HttpPost(alarmCallbackServer);

	        try {
	            httpPost.addHeader("Authorization", getHeader(Localfaceuser,passwork));
	            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
	            httpPost.setEntity(entity);// 设置参数实体
	            @SuppressWarnings("resource")
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

	            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
	            } else {
	                mLogger.info("doBasicAuthPost getStatusCode " + httpResp.getStatusLine().getStatusCode());
	            }
	        } catch (ConnectTimeoutException e) {
	            mLogger.info("doBasicAuthPost ConnectTimeoutException " + e.toString());
	        } catch (UnsupportedEncodingException e) {
	            mLogger.info("doBasicAuthPost UnsupportedEncodingException " + e.toString());
	        } catch (IOException e) {
	            mLogger.info("doBasicAuthPost IOException " + e.toString());
	        } catch (Exception e) {
	            mLogger.info("doBasicAuthPost Exception " + e.toString());
	        }

	        return result;
		
	 }
	 
	 
	 public void savemsgpul(String scenePath,long datelong){
		 Date timestamp = Transformationlong(datelong);
	 }
	 
	 
	 
	 	/**
	     * 构造Basic Auth认证头信息
	     * 
	     * @return
	     */
	    private  String getHeader(String username, String password) {
	        String auth = username + ":" + password;
	        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
	        String authHeader = "Basic " + new String(encodedAuth);
	        return authHeader;
	    }
	    
	    public Date Transformationlong(long datelong){
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        Date date= new Date(datelong);
	        return date;
	    }
	    
	    /**
	     * 保存用户信息
	     */
		public String addUserInformation(MultipartFile file, String name, String sex,
				String phong, String sfzid,String detailed,int state) {
			String url="/home/apache-tomcat-7.0.47/webapps/imguser";
			//获取当前时间
			Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
	        String newData = dateFormat.format(data);
			String fileName=file.getOriginalFilename();
			String newfileName=newData+"01"+fileName;
			File targetFile = new File(url, newfileName);
			 if(!targetFile.exists()){  
		         targetFile.mkdirs();  
		    }  
			    try {  
			         file.transferTo(targetFile); 
			    }catch (Exception e) {  
			         e.printStackTrace();  
			    }
			try {
				String imgurl="/"+"imguser"+'/'+newfileName;
				String urlimglist=url+'/'+newfileName;
				userMapper.addUserInformation(urlimglist,imgurl, name, sex, phong,sfzid, detailed,state);
				String msg="1";
				return msg;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		
		/**
		 * 人脸检测和导入数据
		 * @param state 
		 * @param sfzid 
		 * @throws Throwable 
		 */
		public boolean addWhitePersion(String facepath, String name, String phone,String sex) throws Throwable {
			boolean ret = false;
			 String imgpath = facepath.toLowerCase();
			 if (imgpath.contains(".png")) {
	                imgpath = png2jpg(imgpath);
	            }
			 
			 if (imgpath.contains(".jpg")) {
				 List<String> retList = detectFace(imgpath);
				 if(retList != null && retList.size() == 2){
				 int gender=0;
				 if(sex.equals("男")){
					 gender=1;
				 }
				 /*String txtPath ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
				 String TimeSex=readTxT.readTxtLine(txtPath, 1);
				 String personImportServer =TimeSex+"/api/v1/person/import";
				 String TimeSex2=readTxT.readTxtLine(txtPath, 2);*/
				 /*Shooting sh = new Shooting();
				 sh = pushMapper.selcetShootingname(detailed);
				 String TimeSex=sh.getIpurl();
				 String TimeSex2 = sh.getDbname();
				 String personImportServer =TimeSex+"/api/v1/person/import";
				 long dbid = Long.valueOf(TimeSex2).longValue();*/
				 long dbid =10203;
				 String personImportServer ="http://192.168.1.135:8080/api/v1/person/import";
				 ret = addWhitePersionto(personImportServer, name, gender, dbid, retList.get(0), retList.get(1),phone);
			 }else {
                 mLogger.error("人脸检测失败 " + imgpath);
             }
         }
     
			return ret;
		}
		
		/**
		 * 选择图片人脸检测
		 */
		
		public String addFacePathFist(String facepath){
			String imgpath = facepath.toLowerCase();
			String msg=detectFaceFist(imgpath);
			return msg;
			
		}
		

		public List<String> detectFace(String imgpath) throws Throwable {
			String q="0";
		     String feature = null;
		        String face_image = null;
		        List<String> retList = new ArrayList<String>();
		        String json = null;
		        String TimeSex="http://192.168.1.135:8080";
		        String detectFaceFileServer=TimeSex+"/api/v1/tool/detectFaceInFile";
		        String wximgpath = getdownimg(imgpath);
		        if(wximgpath.equals(q)){
		        	System.out.println("图片地址有问题");
		        	retList=null;
		        	return retList;
		        }else{
		        json = doPostFile(detectFaceFileServer, "file", wximgpath);
		        
		        if (json != null) {
		            //System.out.print(json + "\n");
		            try {
		                JsonParser parser = new JsonParser(); // 创建JSON解析器
		                JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
		                int errorcode = object.get("errorCode").getAsInt();
		                if (errorcode == 0) {
		                    JsonObject dataobject = object.get("data").getAsJsonObject();
		                    if (dataobject != null) {
		                        JsonArray array = dataobject.get("result").getAsJsonArray();
		                        if (array.size() > 0) {
		                            JsonObject subObject = array.get(0).getAsJsonObject();

		                            feature = subObject.get("feature").getAsString();
		                            face_image = subObject.get("face_image").getAsString();
		                            retList.add(feature);
		                            retList.add(face_image);
		                        }
		                    }
		                } else {
		                    mLogger.error("detectFace " + json);
		                }
		            } catch (JsonSyntaxException e) {
		                e.printStackTrace();
		            }
		        } else {
		            mLogger.error("connect detectFace error");
		        }
		        return retList;
		        }
		        
		}

		
		public String doPostFile(String urlStr, String paramName,String filePath) {
			 String result = null;
		        @SuppressWarnings("resource")
		        HttpClient httpclient = new DefaultHttpClient();
		        HttpPost post = new HttpPost(urlStr);
		        post.addHeader("Authorization", getHeader(Localfaceuser, passwork));
		        FileBody fileBody = new FileBody(new File(filePath));
		       
		        StringBody stringBody = null;
		        try {
		            stringBody = new StringBody(paramName);
		        } catch (UnsupportedEncodingException e) {
		            mLogger.info("doPostFile UnsupportedEncodingException " + e.toString());
		        }

		        MultipartEntity entity = new MultipartEntity();
		       
		        entity.addPart("file", fileBody);
		        entity.addPart("desc", stringBody);
		        post.setEntity(entity);

		        HttpResponse httpResp;
				try {
					
					httpResp = httpclient.execute(post);
					if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
						result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
					} else {
						mLogger.info("getStatusCode " + httpResp.getStatusLine().getStatusCode());
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		        httpclient.getConnectionManager().shutdown();
		        return result;
		}
		
		public boolean addWhitePersionto(String personServer, String name,int gender, long dbId, String features, String face_image,String phone) {
	        boolean ret = false;
	        String nubrt ="0";
	        String nubter ="1";
	        Calendar curr = Calendar.getInstance();
			curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
			/*Date date=curr.getTime();  
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");  
			String validTo = sdf2.format(date);*/
			String validTo ="2019-10-10";
	        JsonObject object = new JsonObject();
	        object.addProperty("name", name);
	        object.addProperty("idCard", phone);
	        object.addProperty("gender", gender);
	        object.addProperty("dbid", dbId);
	        object.addProperty("features", features);
	        object.addProperty("imageData", face_image);
			//object.addProperty("validTo", validTo);
	        String jsonstr = object.toString();
	        jsonstr = "[" + jsonstr + "]";

	        String json = doPostJson(personServer, jsonstr);
	        System.out.println(json.toString());
	        if (json != null) {
	            JsonParser parser = new JsonParser(); // 创建JSON解析器
	            object = (JsonObject) parser.parse(json); // 创建JsonObject对象
	            int errorcode = object.get("errorCode").getAsInt();
	            if (errorcode == 0) {
	            	/*String yid =String.valueOf(id);
	            	Uploadfile u =userMapper.addqueryUserById(yid);
	            	String Payment=u.getPayment();
	            	if(Payment.equals(nubrt)){
	            		Date data=new Date();
	        	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        	        String updatetime = dateFormat.format(data);
	            		String yindex ="1";
	            		String examine ="1";
	            		String idnumber = validTo;
	            		userMapper.upexaminetwo(examine,yid,updatetime,idnumber);
	            	}else if (Payment.equals(nubter)) {
	            		Date data=new Date();
	        	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        	        String updatetime = dateFormat.format(data);
	            		String yindex ="1";
	            		String examine ="1";
	            		String idnumber = validTo;
	            		userMapper.upexamine(examine, yindex,yid,updatetime,idnumber);
					}*/
	                ret = true;
	            }
	            mLogger.info(name + "  " +json);
	        } else {
	            mLogger.error("connect addWhitePersion error");
	        }
	        return ret;
		}

		public String doPostJson(String urlStr, String jsonstr) {
	        String result = null;
	        HttpPost httpPost = new HttpPost(urlStr);

	        try {
	            httpPost.addHeader("Authorization", getHeader(Localfaceuser, passwork));
	            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
	            // httpPost.setHeader("Content-Type", "application/json");
	            StringEntity se = new StringEntity(jsonstr, "UTF-8");
	            se.setContentType(CONTENT_TYPE_TEXT_JSON);
	            httpPost.setEntity(se);
	            @SuppressWarnings("resource")
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

	            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实
	            
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
	            } else {
	                mLogger.info("getStatusCode " + httpResp.getStatusLine().getStatusCode());
	            }
	        } catch (ConnectTimeoutException e) {
	            mLogger.info("doPostJson ConnectTimeoutException " + e.toString());
	        } catch (UnsupportedEncodingException e) {
	            mLogger.info("doPostJson UnsupportedEncodingException " + e.toString());
	        } catch (IOException e) {
	            mLogger.info("doPostJson IOException " + e.toString());
	        } catch (Exception e) {
	            mLogger.info("doPostJson Exception " + e.toString());
	        }

	        return result;
		}



		public String detectFaceFist(String imgpath) {
			
		     String feature = null;
		        String face_image = null;
		        List<String> retList = new ArrayList<String>();
		        String json = null;
		        String txtPath ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
				String TimeSex=readTxT.readTxtLine(txtPath, 1);
		        String detectFaceFileServer=TimeSex+"/api/v1/tool/detectFaceInFile";
		        json = doPostFile(detectFaceFileServer, "file", imgpath);
		        if (json != null) {
		                JsonParser parser = new JsonParser(); // 创建JSON解析器
		                JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
		                int errorcode = object.get("errorCode").getAsInt();
		                if (errorcode == 0) {
		                	String msg="1";
		                	return msg;
		                	}else {
								String msg="0";
								return msg;
							}
		        }else{
		        	String msg="0";
		        	return msg;
		        }
		}
		
		/**
		 * 根据用户ID查询用户信息
		 * @throws Throwable 
		 */
		public Returnxx addqueryUserById(String id) throws Throwable {
			String yid= id;
			Uploadfile u =userMapper.addqueryUserById(yid);
			int id2 = u.getYid();
			String urlimglist=u.getYfilename();
			String facepath=urlimglist;
			String sfzid =u.getYphone();
			String sex = u.getYsex();
			String detailed = u.getYaddress();
			String name =u.getYname();
			String phong = u.getYphone();
			String phone=phong;
			String state =u.getYindex();
			//boolean msg = addWhitePersion(facepath, name, phone, detailed, sex,sfzid,state,id2);
			String msg=null;
			Returnxx r = new Returnxx();
			if(msg==null){
				String usermsg="0";
				r.setMsg(usermsg);
				return r;
			}else {
				String usermsg="1";
				r.setMsg(usermsg);
				r.setDetailed(detailed);
				return r;
			}
		}
		
		/**
		 * 更新用户状态
		 */
		public void updateUserState(int id,String state,String validTo){
			String yindex=state;
			String idnumber=validTo;
			Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        String updatetime = dateFormat.format(data);
			userMapper.updateUserState(id,yindex,idnumber,updatetime);
			
		}
		
		/**
		 * 分页查询
		 */
		public void showProductsByPage(String pageNow,String name, Model model) { 	
			System.out.println("分页查询");
		    Page page = null;  
		    List<Uploadfile> products = new ArrayList<Uploadfile>();   
		    List<Unitdoor> unitdoor = new ArrayList<Unitdoor>();
		    List<Shooting> shooting = new ArrayList<Shooting>();
		    String Celladdress1=name;
		    int totalCount = (int) userMapper.getProductsCount(Celladdress1);
		    
		    int totalCount2 = (int) userMapper.getnotProductsCount(Celladdress1);//为审核人数 getyesProductsCount
		    
		    int totalCount3 = (int) userMapper.getyesProductsCount(Celladdress1);
		  
		    if (pageNow != null) {  
		        page = new Page(totalCount, Integer.parseInt(pageNow));  
		        products = this.userMapper.selectProductsByPage(page.getStartPos(),Celladdress1, page.getPageSize());

		    } else {  
		        page = new Page(totalCount, 1);  
		        products = this.userMapper.selectProductsByPage(page.getStartPos(),Celladdress1, page.getPageSize()); 
		   
		    }
		    String address=name;
		    String number ="all";
		    unitdoor = userMapper.selecUnitdoor(address,number);
		    shooting = pushMapper.selcetShooting(address);
		    String Total = String.valueOf(totalCount);
		    
		    String Tota2 = String.valueOf(totalCount2);
		    
		    String Tota3 = String.valueOf(totalCount3);
		    
		    model.addAttribute("shooting",shooting);
		    model.addAttribute("products", products);  
		    model.addAttribute("unitdoor", unitdoor); 
		    model.addAttribute("address", address);
		    model.addAttribute("page", page);
		    model.addAttribute("Total", Total);
		    model.addAttribute("Tota2", Tota2);
		    model.addAttribute("Tota3", Tota3);
		    
			
		}
		
		/**
		 * 彩之云授权人员分页查询
		 */
		public void showProductsByPageczy(String pageNow,String name, Model model) { 	
			System.out.println("分页查询");
		    Page page = null;  
		    List<Visitors> products = new ArrayList<Visitors>();   

		    String Celladdress1=name;
		    int totalCount = (int) userMapper.getProductsCountczy(Celladdress1);
		  
		    if (pageNow != null) {  
		        page = new Page(totalCount, Integer.parseInt(pageNow));  
		        products = this.userMapper.selectProductsByPageczy(page.getStartPos(),Celladdress1, page.getPageSize());

		    } else {  
		        page = new Page(totalCount, 1);  
		        products = this.userMapper.selectProductsByPageczy(page.getStartPos(),Celladdress1, page.getPageSize()); 
		   
		    }
		    String address=name;
		    String Total = String.valueOf(totalCount);
		    model.addAttribute("products", products);  
		    model.addAttribute("address", address);
		    model.addAttribute("Total", Total);
		    model.addAttribute("page", page);
		    
			
		}

	
		/**
		 * 
		 */
	    public long  getUserID(String idCard) {
	    	Uploadfile u =userMapper.addqueryUserById(idCard);
			String phone = u.getYphone();
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        String txtPath ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
	        String TimeSex2=readTxT.readTxtLine(txtPath, 2);
			long dbid = Long.valueOf(TimeSex2).longValue();
	        params.add(new BasicNameValuePair("dbIds", ""+dbid));
	        params.add(new BasicNameValuePair("idCard", phone));
	        long userid=0;
	        //接口不支持精确查询
	        String txtPath1 ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
			String TimeSex=readTxT.readTxtLine(txtPath1, 1);
	        String personQueryServer = TimeSex+"/api/v1/person/query";
	        String json = DeledoBasicAuthPost(personQueryServer, params);
	        if (json != null) {
	            JsonParser parser = new JsonParser(); // 创建JSON解析器
	            JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
	            int errorcode = object.get("errorCode").getAsInt();
	            if (errorcode == 0) {
	                JsonObject dataobject = object.get("data").getAsJsonObject();
	                if (dataobject != null) {
	                    JsonArray array = dataobject.get("content").getAsJsonArray();
	                    for (int i = 0; i < array.size(); i++) {
	                        JsonObject subObject = array.get(i).getAsJsonObject();
	                        String idCard1 = subObject.get("idCard").getAsString();
	                        if (idCard1 != null && idCard1.equals(phone)) {
	                            userid = subObject.get("id").getAsLong();
	                            break;
	                        }
	                    }
	                }
	            }
	        } else {
	           System.out.println("查询出错了");
	        }
	        
	        return userid;
	    }


	    public String DeledoBasicAuthPost(String urlStr, List<NameValuePair> params) {
	        String result = null;
	        HttpPost httpPost = new HttpPost(urlStr);

	        try {
	            httpPost.addHeader("Authorization", getHeader(Localfaceuser, passwork));
	            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
	            httpPost.setEntity(entity);// 设置参数实体
	            @SuppressWarnings("resource")
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

	            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
	            } else {
	                mLogger.info("doBasicAuthPost getStatusCode " + httpResp.getStatusLine().getStatusCode());
	            }
	        } catch (ConnectTimeoutException e) {
	            mLogger.info("doBasicAuthPost ConnectTimeoutException " + e.toString());
	        } catch (UnsupportedEncodingException e) {
	            mLogger.info("doBasicAuthPost UnsupportedEncodingException " + e.toString());
	        } catch (IOException e) {
	            mLogger.info("doBasicAuthPost IOException " + e.toString());
	        } catch (Exception e) {
	            mLogger.info("doBasicAuthPost Exception " + e.toString());
	        }

	        return result;
	    }

	    /**
	     * 删除用户
	     * @param id
	     * @return
	     */
		 public Returnxx Deleuserfin(String id,String phoneidd){
			 	String msg=null;
		        List<NameValuePair> params = new ArrayList<NameValuePair>();
		        Uploadfile up = new Uploadfile();
		        up = userMapper.secletusergunone(phoneidd);
		        String detailed2 = up.getYaddress();
		        String nameone = up.getGun();
		        Shooting sh = new Shooting();
				sh = pushMapper.selcetShootingname(detailed2);
				String TimeSex=sh.getIpurl();
		       /* String txtPath ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
				String TimeSex=readTxT.readTxtLine(txtPath, 1);*/
		        String personDeleServer = TimeSex+"/api/v1/person/"+id;
		        String json =DeledoBasicuser(personDeleServer,params);
		        Returnxx rb = new Returnxx();
		        if (json != null) {
		            JsonParser parser = new JsonParser(); // 创建JSON解析器
		            JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
		            int errorcode = object.get("errorCode").getAsInt();
		            if (errorcode == 0) {
		            	msg="1";
		            	String state1 = "0";
		            	Uploadfile u =userMapper.addqueryUserById(phoneidd);
		            	int id1 = u.getYid();
		            	String detailed =u.getYaddress();
		            	Date date2 = new Date();
		            	SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyyMMdd");
		                String state = dateFormat2.format(date2);
		            	String validTo=state;
		            	String gun = null;
		            	updateUserState(id1,state1,validTo);
		            	rb.setMsg(msg);
		            	rb.setDetailed(detailed);
		            	return rb;
		            	}else{
		            	msg="0";
		            	rb.setMsg(msg);
		            	return rb;
		            	}
		            }else {
						msg="0";
		            	rb.setMsg(msg);
		            	return rb;
					}
			 
			 
		 }

		 
		 
		    public String DeledoBasicuser(String urlStr,List<NameValuePair> params) {
		        String result = null;
		        HttpDelete httpDelete = new HttpDelete(urlStr);

		        try {
		        	httpDelete.addHeader("Authorization", getHeader(Localfaceuser, passwork));
		           // HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集-8");
		            @SuppressWarnings("resource")
		            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
		            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
		            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

		            HttpResponse httpResp = httpClient.execute(httpDelete);// 获取HttpResponse实例
		            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
		                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
		            } else {
		                mLogger.info("doBasicAuthPost getStatusCode " + httpResp.getStatusLine().getStatusCode());
		            }
		        } catch (ConnectTimeoutException e) {
		            mLogger.info("doBasicAuthPost ConnectTimeoutException " + e.toString());
		        } catch (UnsupportedEncodingException e) {
		            mLogger.info("doBasicAuthPost UnsupportedEncodingException " + e.toString());
		        } catch (IOException e) {
		            mLogger.info("doBasicAuthPost IOException " + e.toString());
		        } catch (Exception e) {
		            mLogger.info("doBasicAuthPost Exception " + e.toString());
		        }

		        return result;
		    }
		    
		    /**
		     * 保存推送头像用户信息
		     */
			public String addUserImgToFist(String strimg, String name,
					String sex, String phong, String sfzid, String detailed,
					int state) {
				String url="/home/apache-tomcat-7.0.47/webapps/tdimg/"+strimg;
				String imgurl="/tdimg/"+strimg;
				String urlimglist=url;
				userMapper.addUserInformation(urlimglist,imgurl, name, sex, phong,sfzid, detailed,state);
				String msg ="1";
				return msg;
			}
			/**
			 * 用户列表删除
			 */
			public Returnxx deleimg(String id,String yaddress) {
				Returnxx rb  = new Returnxx();
				String msg= null;
				String yid = id;
				try {
					userMapper.deleimg(yid);
					 msg ="1";
					 rb.setMsg(msg);
					 rb.setDetailed(yaddress);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return rb;
				
			}
			
			/**
			 * 选上传到服务器，再用服务器地址来上传检测人脸
			 */
			public String UserimgUploadFin(MultipartFile file){
				String url="/home/apache-tomcat-7.0.47/webapps/testimg";
				//获取当前时间
				Date data=new Date();
		        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
		        String newData = dateFormat.format(data);
				String fileName=file.getOriginalFilename();
				String newfileName=newData+"01"+fileName;
				File targetFile = new File(url, newfileName);
				 if(!targetFile.exists()){  
			         targetFile.mkdirs();
			    }  
				    try {  
				         file.transferTo(targetFile); 
				    }catch (Exception e) {  
				         e.printStackTrace();  
				    }
				try {
					String imgurl="/"+"testimg"+'/'+newfileName;
					String urlimglist=url+'/'+newfileName;
					String msg=addFacePathFist(urlimglist);
					return msg;
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
			/**
			 * 图片格式转换
			 * @param pngFile
			 * @return
			 */
			public static String png2jpg(String pngFile) {
				String newFile = null;
				if (pngFile != null && pngFile.toLowerCase().contains(".png")) {
					try {
						// read image file
						BufferedImage bufferedImage = ImageIO.read(new File(pngFile));
						newFile = pngFile.replace(".png", ".jpg");
						ImageIO.write(bufferedImage, "jpg", new File(newFile));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				return newFile;
			}
	    
		/**
		 * 通过url下载图片
		 */
		
		public String getdownimg(String wxpath)throws Exception{
			String msg;
			Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
	        String newData = dateFormat.format(data);
			String filename="C:\\testimg\\"+newData+"01"+".jpg";
			try {
				// 构造URL
				URL url = new URL(wxpath);
				// 打开连接
				URLConnection con = url.openConnection();
				// 输入流
				InputStream is = con.getInputStream();
				// 1K的数据缓冲
				byte[] bs = new byte[1024];
				// 读取到的数据长度
				int len;
				// 输出的文件流
				OutputStream os = new FileOutputStream(filename);
				// 开始读取
				while ((len = is.read(bs)) != -1) {
				  os.write(bs, 0, len);
				}
				// 完毕，关闭所有链接
				os.close();
				is.close();
				msg=filename;
				return msg;
			} catch (Exception e) {
				msg="0";
				return msg;
			}
		    
		}

		/**
		 * 没有用到
		 */
		public Returnxx selectFinPhoneorUserName(String yphone,
				String yname) {
			Returnxx tb = new Returnxx();
			return tb;
		}

		/**
		 * 根据用户姓名和手机
		 */
		public void selectFinPhoneorUserNamefin(String phonename,
				String nameonefin, String yaddressallall,String pageNow, Model model) {
			Page page = null;  
		    List<Uploadfile> products = new ArrayList<Uploadfile>();
		    String kz ="";
		    String yphone = phonename;
		    String yname = nameonefin+"%";
		    String yaddress = yaddressallall;
		    List<Shooting> shooting = new ArrayList<Shooting>();
		    
		    if(yphone==null||yphone.equals(kz)){
		    	int totalCount = (int) userMapper.getProductsCount2(yname,yaddress);
				  
			    if (pageNow != null) {  
			        page = new Page(totalCount, Integer.parseInt(pageNow));  
			        products = this.userMapper.selectnameonefinPage(page.getStartPos(),yname,yaddress, page.getPageSize());

			    } else {  
			        page = new Page(totalCount, 1);  
			        products = this.userMapper.selectnameonefinPage(page.getStartPos(),yname,yaddress, page.getPageSize()); 
			   
			    }
			    shooting = pushMapper.selcetShooting(yaddressallall);
			    model.addAttribute("shooting",shooting);
			    model.addAttribute("products", products);
			    model.addAttribute("phonename", phonename); 
			    model.addAttribute("nameonefin", nameonefin); 
			    model.addAttribute("page", page);
			    model.addAttribute("yaddressallall", yaddressallall);
		    }
		    if(yname==null||yname.equals(kz)){
		    	int totalCount = (int) userMapper.getProductsCount3(yphone,yaddress);
				  
			    if (pageNow != null) {  
			        page = new Page(totalCount, Integer.parseInt(pageNow));
			        products = this.userMapper.selectFinPhoneorUserNameu(page.getStartPos(),yphone, yaddress,page.getPageSize());

			    } else {  
			        page = new Page(totalCount, 1);  
			        products = this.userMapper.selectFinPhoneorUserNameu(page.getStartPos(),yphone, yaddress,page.getPageSize()); 
			   
			    }
			    shooting = pushMapper.selcetShooting(yaddressallall);
			    model.addAttribute("shooting",shooting);
			    model.addAttribute("products", products);
			    model.addAttribute("phonename", phonename); 
			    model.addAttribute("nameonefin", nameonefin); 
			    model.addAttribute("page", page);
			    model.addAttribute("yaddressallall", yaddressallall);
		    }
		    if(yphone!=null&&!yphone.equals(kz)&&yname!=null&&!yname.equals(kz)){
		    	int totalCount = (int) userMapper.getProductsCount4(yphone,yname,yaddress);
			    if (pageNow != null) {  
			        page = new Page(totalCount, Integer.parseInt(pageNow));  
			        products = this.userMapper.selectallFInPage(page.getStartPos(),yphone,yname,yaddress, page.getPageSize());

			    } else {  
			        page = new Page(totalCount, 1);  
			        products = this.userMapper.selectallFInPage(page.getStartPos(),yphone,yname, yaddress,page.getPageSize()); 
			   
			    }
			    shooting = pushMapper.selcetShooting(yaddressallall);
			    model.addAttribute("shooting",shooting);
			    model.addAttribute("products", products);  
			    model.addAttribute("phonename", phonename); 
			    model.addAttribute("nameonefin", nameonefin); 
			    model.addAttribute("page", page);
			    model.addAttribute("yaddressallall", yaddressallall);
		    }
		  
		}
		/**
		 * 根据条件查询用户信息
		 */
		public List<Uploadfile> selectloufin(String yid) {
			List<Uploadfile> products = new ArrayList<Uploadfile>();
			products = userMapper.selecfinuserlou(yid);
			return products;
		}

		public List<Unitdoor> selectloufinuser(String yaddressallall) {
			List<Unitdoor> unitdoor = new ArrayList<Unitdoor>();
			String address = yaddressallall;
			String number ="all";
			unitdoor = userMapper.selecUnitdoor(address,number);
			return unitdoor;
		}

		/**
		 * 用户单元楼和用户姓名更新
		 */
		public Returnxx UpselcetUserXxFin(int yid, String ydetailed,String yaddress,String yname,String cardnumber,String yidcar,String roomandnumber,String unitbuilding) {
			List<Uploadfile>listandcardnumber=userMapper.seleuserandcardnumber(cardnumber,yaddress);
			Returnxx rb  = new Returnxx();
			String msg =null;
			String detailed = null;
			if(cardnumber.equals("")||cardnumber==null){//卡号为空
				try {
					Date data=new Date();
					SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String updatetime = dateFormat.format(data);
					userMapper.UpselectFinto(yname, ydetailed, yid,updatetime,cardnumber,yidcar,roomandnumber,unitbuilding);
					msg ="1";
					detailed=yaddress;
				} catch (Exception e) {
					msg="0";
					rb.setMsg(msg);
					return rb;
				}
					
				rb.setDetailed(detailed);
				rb.setMsg(msg);
				return rb;
			}else {//卡号不为空
				String id=String.valueOf(yid);
				Uploadfile upto=userMapper.selecfinuserlouto(id);
				String cardnumberto = upto.getCardnumber();//原来用户卡号
				if(cardnumberto==null){
					try {
						Date data=new Date();
						SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String updatetime = dateFormat.format(data);
						userMapper.UpselectFinto(yname, ydetailed, yid,updatetime,cardnumber,yidcar,roomandnumber,unitbuilding);
						msg ="1";
						detailed=yaddress;
					} catch (Exception e) {
						msg="0";
						rb.setMsg(msg);
						return rb;
					}
					
					rb.setDetailed(detailed);
					rb.setMsg(msg);
					return rb;
				}else {
				
					try {
						Date data=new Date();
						SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String updatetime = dateFormat.format(data);
						userMapper.UpselectFinto(yname, ydetailed, yid,updatetime,cardnumber,yidcar,roomandnumber,unitbuilding);
						msg ="1";
						detailed=yaddress;
					} catch (Exception e) {
						msg="0";
						rb.setMsg(msg);
						return rb;
					}
						
					rb.setDetailed(detailed);
					rb.setMsg(msg);
					return rb;
			
			}
			}
			
			/*List<Uploadfile>listandcardnumber=userMapper.seleuserandcardnumber(cardnumber,yaddress);
			Returnxx rb  = new Returnxx();
			String msg =null;
			String detailed = null;
			if(cardnumber.equals("")||cardnumber==null){//卡号为空
				try {
					Date data=new Date();
					SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String updatetime = dateFormat.format(data);
					userMapper.UpselectFinto(yname, ydetailed, yid,updatetime,cardnumber,yidcar,roomandnumber,unitbuilding);
					msg ="1";
					detailed=yaddress;
				} catch (Exception e) {
					msg="0";
					rb.setMsg(msg);
					return rb;
				}
					
				rb.setDetailed(detailed);
				rb.setMsg(msg);
				return rb;
			}else {//卡号不为空
				String id=String.valueOf(yid);
				Uploadfile upto=userMapper.selecfinuserlouto(id);
				String cardnumberto = upto.getCardnumber();//原来用户卡号
				if(cardnumberto==null){
					try {
						Date data=new Date();
						SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String updatetime = dateFormat.format(data);
						userMapper.UpselectFinto(yname, ydetailed, yid,updatetime,cardnumber,yidcar,roomandnumber,unitbuilding);
						msg ="1";
						detailed=yaddress;
					} catch (Exception e) {
						msg="0";
						rb.setMsg(msg);
						return rb;
					}
					
					rb.setDetailed(detailed);
					rb.setMsg(msg);
					return rb;
				}else {
				if(cardnumberto.equals(cardnumber)){//跟之前卡号一样
					try {
						Date data=new Date();
						SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String updatetime = dateFormat.format(data);
						userMapper.UpselectFinto(yname, ydetailed, yid,updatetime,cardnumber,yidcar,roomandnumber,unitbuilding);
						msg ="1";
						detailed=yaddress;
					} catch (Exception e) {
						msg="0";
						rb.setMsg(msg);
						return rb;
					}
						
					rb.setDetailed(detailed);
					rb.setMsg(msg);
					return rb;
				}else {//跟之前的卡号不一样
					
					if(listandcardnumber.size()==0){//查询卡号是否重复
						try {
							Date data=new Date();
							SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String updatetime = dateFormat.format(data);
							userMapper.UpselectFinto(yname, ydetailed, yid,updatetime,cardnumber,yidcar,roomandnumber,unitbuilding);
							msg ="1";
							detailed=yaddress;
						} catch (Exception e) {
							msg="0";
							rb.setMsg(msg);
							return rb;
						}
						
						rb.setDetailed(detailed);
						rb.setMsg(msg);
						return rb;
					}else {
						msg="400";
						rb.setDetailed(detailed);
						rb.setMsg(msg);
						return rb;
					}
				}
			}
			}*/
			
		}
		/**
		 * 更新到期用户
		 */
		public void TimeLod(String index, String idnumber) {
			System.out.println(userMapper);
			userMapper.UpselectFintotime(index,idnumber);
			System.out.println("123");
			
		}
		
		/**
		 * 卡号注册
		 */
		public Returnxx savekahaouser(String yname, String ysex,String cardnumber, String yaddress, String ydetailed) {
			List<Uploadfile>listandcardnumber=userMapper.seleuserandcardnumber(cardnumber,yaddress);
			Returnxx rb  = new Returnxx();
			String msg=null;
			String detailed=null;
			/*if(listandcardnumber.size()==0){*/
				try {
					String yindex="1";
					String idnumber="30001010";
					Date data=new Date();
			        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        String updatetime = dateFormat.format(data);
			        String examine = "1";
					userMapper.savekahaouser(yname, ysex, cardnumber, yaddress, ydetailed,yindex,idnumber,updatetime,examine);
					msg ="1";
					detailed=yaddress;
				} catch (Exception e) {
					 msg="0";
					rb.setMsg(msg);
					return rb;
				}
				
			/*}else {
					msg="400";
					detailed=yaddress;
				}*/
			
			rb.setDetailed(detailed);
			rb.setMsg(msg);
			return rb;
			}
				
			
		
		
		/**
		 * 管理员卡号注册
		 */
		public Returnxx savekahaouserandadmin(String yname, String ysex,
				String cardnumber, String yaddress) {
			String msg= null;
			String detailed=null;
			Returnxx rb  = new Returnxx();
			List<Uploadfile>listandcardnumber=userMapper.seleuserandcardnumber(cardnumber,yaddress);
			if(listandcardnumber.size()==0){
				try {
					String yindex="1";
					String idnumber="30001010";
					Date data=new Date();
					SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String updatetime = dateFormat.format(data);
					String examine = "1";
					String ydetailed="0";
					userMapper.savekahaouser(yname, ysex, cardnumber, yaddress, ydetailed,yindex,idnumber,updatetime,examine);
					msg ="1";
					detailed=yaddress;
				} catch (Exception e) {
					 msg="0";
					rb.setMsg(msg);
					return rb;
					
				}	
				
			}else {
				msg="400";
				detailed=yaddress;
			}
			
			rb.setDetailed(detailed);
			rb.setMsg(msg);
			return rb;
		}
		
		
		/**
		 * 允许用户更新状态
		 */
		public Returnxx upuseronetwonuber(String  idone){
			String ynumber ="2";
			Returnxx rb  = new Returnxx();
			String nubrt ="0";
	        String nubter ="1";
	        Calendar curr = Calendar.getInstance();
			curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);//当前日期加上一年
			Date date=curr.getTime();  
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");  
			String validTo = sdf2.format(date);
			String yid =idone;
        	Uploadfile u =userMapper.addqueryUserById(yid);
        	String Payment=u.getPayment();
        	String detailed=u.getYaddress();
        	String yaddress =detailed;
        	//User userone = new User();
        	Location userone = new Location();
        	userone = userMapper.seclectfinusermoeny(yaddress);
        	String moeny=userone.getMoeny();
        	if(moeny.equals("0")){//判断小区是不是采取收费的政策
        		Date data=new Date();
    	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	        String updatetime = dateFormat.format(data);
        		String yindex ="1";
        		String examine ="1";
        		String idnumber = validTo;
        		userMapper.upexamine(examine, yindex,yid,updatetime,idnumber);	
        	}else {
        		if(Payment.equals(nubrt)){//判断是否已经交费
            		Date data=new Date();
        	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        	        String updatetime = dateFormat.format(data);
            		String examine ="1";
            		String idnumber = validTo;
            		userMapper.upexaminetwo(examine,yid,updatetime,idnumber);
            		
        			
            	}else if (Payment.equals(nubter)) {//判断是否已经交费
            		Date data=new Date();
        	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        	        String updatetime = dateFormat.format(data);
            		String yindex ="1";
            		String examine ="1";
            		String idnumber = validTo;
            		userMapper.upexamine(examine, yindex,yid,updatetime,idnumber);
    			}
			}	
        	String msg="1";
			rb.setDetailed(detailed);
			rb.setMsg(msg);
    		return rb;
			
		}
		
		
		/**
		 * 删除用户
		 */
	public Returnxx deleonetwonuber(int idone){
		String yid =String.valueOf(idone);
		Uploadfile u =userMapper.addqueryUserById(yid);
    	String detailed=u.getYaddress();
		Returnxx rb  = new Returnxx();
		String examine="0";
		String yindex= "0";
		Date data=new Date();
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String updatetime = dateFormat.format(data);
        Date data2=new Date();
        SimpleDateFormat dateFormattwo=new SimpleDateFormat("yyyyMMdd");
        String idnumber = dateFormattwo.format(data2);
        userMapper.upexaminedele(examine, yindex,yid,updatetime);
        String msg="1";
		rb.setDetailed(detailed);
		rb.setMsg(msg);
		return rb;
	}
	
	/**
	 * 分页查询告警
	 */
	public void showwubohui(String pageNow, Model model) { 	    
	    Page page = null;  
	    List<pathuser> products = new ArrayList<pathuser>();   

	    int totalCount = (int) userMapper.getProductsCountwubohui();
	  
	    if (pageNow != null) {  
	        page = new Page(totalCount, Integer.parseInt(pageNow));  
	        products = this.userMapper.selectProductsByPagewubohui(page.getStartPos(), page.getPageSize());

	    } else {  
	        page = new Page(totalCount, 1);  
	        products = this.userMapper.selectProductsByPagewubohui(page.getStartPos(), page.getPageSize()); 
	   
	    }
	    model.addAttribute("products", products); 
	    model.addAttribute("totalCount", totalCount);
	    
	    
		
	}
	
	/**
	 * 
	 */
	
	public test1 showwubohui2(){
		test1 t = new test1();
		List<pathuser> products = new ArrayList<pathuser>();   
		Page page = null;  
		int totalCount = (int) userMapper.getProductsCountwubohui();
		page = new Page(totalCount, 1);  
        products = this.userMapper.selectProductsByPagewubohui(page.getStartPos(), page.getPageSize());
        t.setList(products);
        t.setNuber(totalCount);
        return t;
	}

	public void showFastregistrationcardnumberrepeating(String pageNow,
			String address, Model model) {
		System.out.println("分页查询");
	    Page page = null;  
	    List<Uploadfile> products = new ArrayList<Uploadfile>();   
	    List<Unitdoor> unitdoor = new ArrayList<Unitdoor>();
	    List<Shooting> shooting = new ArrayList<Shooting>();
	    String yaddress=address;
	    int totalCount = (int) userMapper.getFastregistrationcardnumberrepeating(yaddress);
	  
	    if (pageNow != null) {  
	        page = new Page(totalCount, Integer.parseInt(pageNow));  
	        products = this.userMapper.selectFastregistrationcardnumberrepeatingPage(page.getStartPos(),yaddress, page.getPageSize());

	    } else {  
	        page = new Page(totalCount, 1);  
	        products = this.userMapper.selectFastregistrationcardnumberrepeatingPage(page.getStartPos(),yaddress, page.getPageSize()); 
	   
	    }
	    String number ="all";
	    unitdoor = userMapper.selecUnitdoor(address,number);
	    shooting = pushMapper.selcetShooting(address);
	    model.addAttribute("shooting",shooting);
	    model.addAttribute("products", products);  
	    model.addAttribute("unitdoor", unitdoor); 
	    model.addAttribute("address", address);
	    model.addAttribute("page", page);
		
	}
	
	/**
	 * 修改密码
	 */
	public Returnxx modifythepasswordtolike(String yuan, String xin,
			String leixin, String yaddress) {
		Returnxx rb  = new Returnxx();
		String ynumber=leixin;
		String ypassword=xin;
		String msg=null;
		String msgto ="400";
		Usero usero = new Usero();
		try {
			usero = userMapper.seleusermima(ynumber, yaddress);//类型+小区地址查询密码
		} catch (Exception e) {
			rb.setMsg(msgto);
			e.printStackTrace();
		}
		String mima=usero.getYpassword();
		if(yuan.equals(mima)){//原密码相同
			userMapper.upusermimato(ypassword,ynumber,yaddress);
			 msg="1";
		}else {//不相同
			msg="2";
		}
		rb.setMsg(msg);
		rb.setDetailed(yaddress);
		return rb;
	}

	/**
	 * 增量备份
	 */
	public String Incrementalandbackupservice(String starttime, String endtime) {
		String msg = "成功";
		String benurl=null;
		String  un =null;
		String yfilenameto=null;
		List<Location>listone = userMapper.selectandLocationtoaddress();
		for (int i = 0; i < listone.size(); i++) {
			String yaddress=listone.get(i).getAddress();
			if(yaddress.equals("测试地址")){
				
			}else if(yaddress.equals("测试小区")) {
				
			}else if (yaddress.equals("测试地址")) {
				
			}else if (yaddress.equals("彩悦大厦")) {
				
			}else if (yaddress.equals("花样年华乡")) {
				
			}else if (yaddress.equals("深圳花乡")) {
				
			}else {
				
				List<Uploadfile>listtwo = userMapper.selectandUploadfiletoaddress(yaddress,starttime,endtime);
				for (int j = 0; j < listtwo.size(); j++) {
					String yfilename=listtwo.get(j).getYfilename();//图片路径
					System.out.println("=========================>"+j+yaddress);
					if(yfilename==null){
						//没有图片路径的不做操作
						System.out.println("为空");
					}else {
						try {
						String nmn=null;
						String lo=panduanString(yfilename);
						/*String a="upload";
						String b="wx";
						String c="czy";
						String d="grant";*/
						
						if(lo=="upload"){
							un = "https://wwl.ycws.cc/image/upload/";
							yfilenameto=yfilename.replaceAll(un, "");//图片名字
							benurl="E:/imgbz/upload/"+yfilenameto;
							//benurl="E:/imgbz/111/"+yfilenameto;
							 nmn=getdownimgincre(yfilename,benurl);
						}else if(lo=="wx") {
							un = "https://wwl.ycws.cc/image/wx/";
							yfilenameto=yfilename.replaceAll(un, "");//图片名字
							benurl="E:/imgbz/wx/"+yfilenameto;
							 nmn=getdownimgincre(yfilename,benurl);
						}else if(lo=="czy"){
							un = "https://wwl.ycws.cc/image/czy/";
							yfilenameto=yfilename.replaceAll(un, "");//图片名字
							benurl="E:/imgbz/czy/"+yfilenameto;
							 nmn=getdownimgincre(yfilename,benurl);
						}else if(lo=="grant"){
							un = "https://wwl.ycws.cc/image/grant/";
							yfilenameto=yfilename.replaceAll(un, "");//图片名字
							benurl="E:/imgbz/grant/"+yfilenameto;
							 nmn=getdownimgincre(yfilename,benurl);
						}
						else {
							//不符合的不做操作
						}
						
						
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				
			}
			List<Visitors>listtwof = userMapper.selectandvisitorstoaddress(yaddress,starttime,endtime);
			for (int m = 0; m< listtwof.size(); m++) {
				String yfilename=listtwof.get(m).getYimageurl();//图片路径
				if(yfilename==null){
					//没有图片路径的不做操作
					System.out.println("为空");
				}else {
					try {
					String nmnt=null;
					String lo=panduanString(yfilename);
					/*String a="upload";
					String b="wx";
					String c="czy";
					String d="grant";*/
					if(lo=="upload"){
						un = "https://wwl.ycws.cc/image/upload/";
						yfilenameto=yfilename.replaceAll(un, "");//图片名字
						benurl="E:/imgbz/upload/"+yfilenameto;
						 nmnt=getdownimgincre(yfilename,benurl);
					}else if(lo=="wx") {
						un = "https://wwl.ycws.cc/image/wx/";
						yfilenameto=yfilename.replaceAll(un, "");//图片名字
						benurl="E:/imgbz/wx/"+yfilenameto;
						 nmnt=getdownimgincre(yfilename,benurl);
					}else if(lo=="czy"){
						un = "https://wwl.ycws.cc/image/czy/";
						yfilenameto=yfilename.replaceAll(un, "");//图片名字
						benurl="E:/imgbz/czy/"+yfilenameto;
						 nmnt=getdownimgincre(yfilename,benurl);
					}else if(lo=="grant"){
						un = "https://wwl.ycws.cc/image/grant/";
						yfilenameto=yfilename.replaceAll(un, "");//图片名字
						benurl="E:/imgbz/grant/"+yfilenameto;
						 nmnt=getdownimgincre(yfilename,benurl);
					}
					else {
						//不符合的不做操作
					}
					
					
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			
			
		}
		
		
		return msg;
	}
	
	/**
	 * 通过url下载图片
	 */
	public  String getdownimgincre(String yfilename,String benurl)throws Exception{
		Date data=new Date();
		String filename;
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String newData = dateFormat.format(data);
		try {
			filename=benurl;
			// 构造URL
			URL url = new URL(yfilename);
			// 打开连接
			URLConnection con = url.openConnection();
			// 输入流
			InputStream is = con.getInputStream();
			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			OutputStream os = new FileOutputStream(filename);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
			  os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
			filename=null;
		}
	    return filename;
	}
	
	/**
	 * 判断字符中是否存在某个字符
	 * @param str
	 * @param stw
	 * @return
	 */
	public String panduanString(String str){
			String mso=null;
			String a="upload";
			String b="wx";
			String c="czy";
			String d="grant";
			String kb="_";
			String kc="-";
			
	        //boolean status = str.contains(stw);  
			boolean status1 = str.contains(a);
			boolean status2 = str.contains(b);
			boolean status3 = str.contains(c);
			boolean status6 = str.contains(d);
			//boolean status4 = str.contains(kb);
			boolean status5 = str.contains(kc);
	        /*if(status){  
	            //System.out.println("包含"); 
	            mso=stw;
	        }else{  
	            //System.out.println("不包含");  
	            mso="2";
	        }*/  
	        if(status5){
	        	mso="错误";
	        }else {
	        	if(status1){
	        		mso=a;
	        	}else if(status2){
	        		mso=b;
	        	}else if(status3){
	        		mso=c;
	        	}else if(status6){
	        		mso=d;
	        	}else {
	        		mso="错误";
	        	}
			}
	        
	        return mso;
	}
	
	/**
	 * 对彩之云的
	 */
	public Returnxx upuserczy(String id,String auto,String detailed) {
		String yid = id;
		String yindate = null;
		Returnxx rb = new Returnxx();
		String msg = null;
		if(auto.equals("1")){//允许
			yindate="1";
		}else {//禁止
			yindate="0";
		}
		try {
			Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        String updatetime = dateFormat.format(data);
			String yupdatetime =updatetime;
			userMapper.upuserczy(yid,yindate,yupdatetime);
			msg="1";
		} catch (Exception e) {
			msg="0";//失败
			e.printStackTrace();
		}
		
		rb.setDetailed(detailed);
		rb.setMsg(msg);
		return rb;
	}

	@Override
	public void Testtime() throws Exception {
		/*Date date = new Date();
		SimpleDateFormat dateFort = new SimpleDateFormat("yyyy-MM-dd");
		String timeone = dateFort.format(date);
		Date date1 = dateFort.parse(timeone);
		Date date3 = new Date(date1.getTime() + 180L * 24L * 60L * 60L * 1000L);
		String d3 = dateFort.format(date3);
        System.out.println(d3);
		 Calendar cal = Calendar.getInstance();
	        cal.setTime(date1);
	        cal.add(Calendar.YEAR, 1);
	        Date date4 = cal.getTime();
	        String d4 = dateFort.format(date4);
	        System.out.println(d4);*/
		
		
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		
		String dateString = "20180102";
		try {
		Date date = df.parse(dateString);
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat dateFort = new SimpleDateFormat("yyyy-MM-dd");
        cal.setTime(date);
        cal.add(Calendar.YEAR, 1);
        Date date4 = cal.getTime();
        String d4 = dateFort.format(date4);
        System.out.println(d4);
		}
		catch (Exception ex)
		{ System.out.println(ex.getMessage());}
		
		
	}
}
